﻿using System;
using System.Linq;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using NLog;
using SiteServer.Plugin;
using SS.Form.Core;
using SS.Form.Core.Model;
using SS.Form.Core.Utils;
using LogManager = SS.Form.Core.LogManager;

namespace SS.Form.Controllers.Pages
{
    [RoutePrefix("pages/logsLayerReply")]
    public class PagesLogsLayerReplyController : ApiController
    {
        private const string Route = "";
        static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        
        [HttpGet, Route(Route)]
        public IHttpActionResult Get()
        {
            try
            {
                var request = Context.AuthenticatedRequest;

                var formInfo = FormManager.GetFormInfoByGet(request);
                if (formInfo == null) return NotFound();
                if (!request.IsAdminLoggin || !request.AdminPermissions.HasSitePermissions(formInfo.SiteId, FormUtils.MenuFormsPermission)) return Unauthorized();

                var logId = request.GetQueryInt("logId");
                var fieldInfoList = FieldManager.GetFieldInfoList(formInfo.Id);
                var logInfo = LogManager.Repository.GetLogInfo(logId);

                var attributeNames = FormManager.GetAllAttributeNames(fieldInfoList);
                if (!logInfo.IsReplied)
                {
                    attributeNames.Remove(nameof(LogInfo.ReplyDate));
                }
                attributeNames.Remove(nameof(LogInfo.ReplyContent));

                return Ok(new
                {
                    Value = logInfo.ToDictionary(),
                    AttributeNames = attributeNames
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost, Route(Route)]
        public IHttpActionResult Submit()
        {
            try
            {
                var request = Context.AuthenticatedRequest;

                var formInfo = FormManager.GetFormInfoByPost(request);
                if (formInfo == null) return NotFound();
                if (!request.IsAdminLoggin || !request.AdminPermissions.HasSitePermissions(formInfo.SiteId, FormUtils.MenuFormsPermission)) return Unauthorized();

                var logId = request.GetPostInt("logId");
                var logInfo = LogManager.Repository.GetLogInfo(logId);
                if (logInfo == null) return NotFound();

                logInfo.ReplyContent = request.GetPostString("replyContent");
                
                LogManager.Repository.Reply(formInfo, logInfo);
                
                //填写回复表单字段加，获取手机号，给用户发送短信
                //if (formId == 1)
                //{
                    //留言内容
                    //var fieldInfoList = FieldManager.GetFieldInfoList(formInfo.Id);
                    //FieldInfo fieldInfo = fieldInfoList.Where(p => p.Title == "手机号码").FirstOrDefault();
                    //FieldInfo fieldInfoReply = fieldInfoList.Where(p => p.Title == "留言内容").FirstOrDefault();
                    
                    if (logInfo != null &&  !string.IsNullOrEmpty(logInfo.ReplyContent))
                    {
                        string attributeValues = logInfo.AttributeValues;
                        JObject jsonObject = JObject.Parse(attributeValues);
                        //获取回复的内容
                        string mobile = (string)jsonObject["手机号码"];
                        Logger.Info("mobile:"+mobile);
                        if (!string.IsNullOrEmpty(mobile) )
                        {
                            Logger.Info("ReplyContent:"+logInfo.ReplyContent);
                            string content = string.Format("【浙大四院】尊敬的市民，您好！您于 {0}反馈的投诉建议已受理。感谢您的监督，祝您健康顺遂！",DateTime.Now.ToString("yyyy年MM月dd日"));
                            SendSmsHelper.SendSms(mobile, content);
                        }
                    }
                    else
                    {
                        Logger.Info("mobile:无找到");
                    }
                //}

                return Ok(new{});
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }
}
